#include <head.h>

int balance = 1000; // 银行余额

// 定义线程号
pthread_t tid[2];
// 定义无名信号量
sem_t sem;
// 定义互斥锁
pthread_mutex_t mutex;

// 定义线程函数
void *withdraw(void *val);

int main()
{
    // 初始化无名信号量
    sem_init(&sem, 0, 1);
    // 初始化互斥锁
    pthread_mutex_init(&mutex, NULL);

    int draw_m1;
    int draw_m2;
    printf("请输入取款金额：");
    scanf("%d", &draw_m1);
    printf("请输入取款金额：");
    scanf("%d", &draw_m2);
    // 创建线程
    pthread_create(&tid[0], NULL, withdraw, (void *)&draw_m1);
    pthread_create(&tid[1], NULL, withdraw, (void *)&draw_m2);

    // 回收线程
    for (size_t i = 0; i < 2; i++)
    {
        pthread_join(tid[i], NULL);
    }

    // 销毁无名信号量
    sem_destroy(&sem);
    // 销毁互互斥锁
    pthread_mutex_destroy(&mutex);

    return 0;
}

// 线程函数
void *withdraw(void *val)
{

    int withdraw_amount = *((int *)val);
    sem_wait(&sem);
    if (balance >= withdraw_amount)
    {
        balance = balance - withdraw_amount;
        printf("取款成功，余额剩余：%d\n", balance);
    }
    else
    {
        printf("取款失败，余额不足\n");
    }
    sleep(1); // 让线程运行1秒，模拟取款操作的持续时间
    sem_post(&sem);
    pthread_mutex_unlock(&mutex);
    return NULL;
}
